package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.cache.GuiGuCache;
import com.atguigu.tingshu.model.album.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"all"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;


    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;


    /**
     * 获取所有分类列表
     *
     * @return
     */
    @Override
    @GuiGuCache(prefix = "category:all:")
    public List<JSONObject> getBaseCategoryList() {
        //1.创建用来保存所有"1级"分类List集合
        List<JSONObject> list = new ArrayList<>();
        //2.查询所有分类视图，共计得到401条记录
        List<BaseCategoryView> allCategoryViewList = baseCategoryViewMapper.selectList(null);

        //3.处理1级分类
        //3.1 对所有分类视图使用Stream流进行分组得到Map<1级分类ID，List<"1级分类对象">>，分组条件：category1Id
        Map<Long, List<BaseCategoryView>> map1 = allCategoryViewList
                .stream()
                .collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));

        //3.2 遍历Map<分组ID，List<"1级分类对象">>，封装"1级分类JSON对象"
        for (Map.Entry<Long, List<BaseCategoryView>> entry1 : map1.entrySet()) {
            //3.2.1 封装"1级分类JSON对象"
            JSONObject jsonObject1 = new JSONObject();
            //3.2.2 获取"1级分类ID"
            Long category1Id = entry1.getKey();
            //3.2.3 获取"1级分类名称"
            String category1Name = entry1.getValue().get(0).getCategory1Name();
            //3.2.4 封装一级分类对象中属性
            jsonObject1.put("categoryId", category1Id);
            jsonObject1.put("categoryName", category1Name);
            //4. 处理2级分类
            //4.1 创建保存"2级分类"List集合
            List<JSONObject> jsonObject2List = new ArrayList<>();
            //4.2 对"1级分类列表"根据二级分类ID进行分组
            Map<Long, List<BaseCategoryView>> map2 = entry1.getValue()
                    .stream()
                    .collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));

            //4.3 遍历二级分类Map，创建二级分类JSON对象
            for (Map.Entry<Long, List<BaseCategoryView>> entry2 : map2.entrySet()) {
                //4.3.1 创建二级分类JSON对象
                JSONObject jsonObject2 = new JSONObject();
                //4.3.2 获取二级分类ID
                Long category2Id = entry2.getKey();
                //4.3.3 获取二级分类名称
                String category2Name = entry2.getValue().get(0).getCategory2Name();
                //4.3.4 封装二级分类对象中属性
                jsonObject2.put("categoryId", category2Id);
                jsonObject2.put("categoryName", category2Name);
                jsonObject2List.add(jsonObject2);
                //5. 处理3级分类
                //5.1 创建保存"3级分类"List集合
                List<JSONObject> jsonObject3List = new ArrayList<>();
                //5.2 遍历"二级分类"集合，创建三级分类JSON对象
                for (BaseCategoryView baseCategoryView : entry2.getValue()) {
                    //5.2.1 创建3级分类JSON对象
                    JSONObject jsonObject3 = new JSONObject();
                    //5.2.2 获取三级分类ID
                    Long category3Id = baseCategoryView.getCategory3Id();
                    //5.2.3 获取三级分类名称
                    String category3Name = baseCategoryView.getCategory3Name();
                    //5.2.4 封装三级分类对象中属性
                    jsonObject3.put("categoryId", category3Id);
                    jsonObject3.put("categoryName", category3Name);
                    //5.2.5 将三级分类对象添加到二级分类对象中
                    jsonObject3List.add(jsonObject3);
                }
                //5.3 将三级分类集合加入到二级分类对象"categoryChild"中
                jsonObject2.put("categoryChild", jsonObject3List);
            }
            //4.4 将二级分类集合加入到一级分类对象"categoryChild"中
            jsonObject1.put("categoryChild", jsonObject2List);
            //3.3 将"1级分类JSON对象"添加到List集合中
            list.add(jsonObject1);
        }
        return list;
    }

    @Autowired
    private BaseAttributeMapper baseAttributeMapper;

    /**
     * 根据1级分类ID查询标签列表（包含标签值）
     *
     * @param category1Id
     * @return
     */
    @Override
    @GuiGuCache(prefix = "category:attribute:")
    public List<BaseAttribute> findAttributeList(Long category1Id) {
        return baseAttributeMapper.findAttributeList(category1Id);
    }

    /**
     * 根据三级分类ID获取分类视图
     *
     * @param category3Id
     * @return
     */
    @Override
    @GuiGuCache(prefix = "category:info:")
    public BaseCategoryView getCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    /**
     * 根据一级分类Id查询置顶7个三级分类列表
     *
     * @param category1Id
     * @return
     */
    @Override
    @GuiGuCache(prefix = "category:topCategory3:")
    public List<BaseCategory3> findTopBaseCategory3(Long category1Id) {
        //1.根据1级分类ID查询该1级分类下二级分类ID列表
        List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(
                new LambdaQueryWrapper<BaseCategory2>()
                        .eq(BaseCategory2::getCategory1Id, category1Id)
                        .select(BaseCategory2::getId)
        );
        if (CollUtil.isNotEmpty(baseCategory2List)) {
            List<Long> category2IdList = baseCategory2List.stream()
                    .map(BaseCategory2::getId).collect(Collectors.toList());
            //2.根据二级分类ID列表查询置顶前7个个三级分类列表
            LambdaQueryWrapper<BaseCategory3> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(BaseCategory3::getCategory2Id, category2IdList);
            queryWrapper.eq(BaseCategory3::getIsTop, 1);
            queryWrapper.orderByAsc(BaseCategory3::getOrderNum);
            queryWrapper.last("limit 7");
            return baseCategory3Mapper.selectList(queryWrapper);
        }

        return null;
    }

    /**
     * 查询1级分类下包含所有二级以及三级分类
     *
     * @param category1Id
     * @return 一级分类对象
     */
    @Override
    @GuiGuCache(prefix = "category:category1:")
    public JSONObject getBaseCategoryListByCategory1Id(Long category1Id) {
        //1.处理1级分类
        //1.1 根据1级分类ID查询分类视图得到所有"1级分类"列表
        List<BaseCategoryView> baseCategory1List = baseCategoryViewMapper.selectList(
                new LambdaQueryWrapper<BaseCategoryView>()
                        .eq(BaseCategoryView::getCategory1Id, category1Id)
        );
        if (CollUtil.isNotEmpty(baseCategory1List)) {
            BaseCategoryView baseCategoryView = baseCategory1List.get(0);
            //1.2 创建1级分类JSON对象
            JSONObject jsonObject1 = new JSONObject();
            //1.2.1 封装1级分类ID
            jsonObject1.put("categoryId", baseCategoryView.getCategory1Id());
            //1.2.2 封装1级分类名称
            jsonObject1.put("categoryName", baseCategoryView.getCategory1Name());

            //2.处理2级分类
            //2.1 对"1级分类列表"按二级分类ID进行分组，得到Map
            Map<Long, List<BaseCategoryView>> map2 = baseCategory1List
                    .stream()
                    .collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));

            //2.2 遍历Map，创建二级分类JSON对象集合
            List<JSONObject> jsonObject2List = new ArrayList<>();
            for (Map.Entry<Long, List<BaseCategoryView>> entry2 : map2.entrySet()) {
                //2.2.1 创建二级分类JSON对象
                JSONObject jsonObject2 = new JSONObject();
                //2.2.2 封装二级分类ID
                Long category2Id = entry2.getKey();
                //2.2.3 封装二级分类名称
                String category2Name = entry2.getValue().get(0).getCategory2Name();
                jsonObject2.put("categoryId", category1Id);
                jsonObject2.put("categoryName", category2Name);
                //3.处理3级分类
                //3.1 创建3级分类JSON对象集合
                List<JSONObject> jsonObject3List = new ArrayList<>();
                //3.2 遍历"2级分类列表"，封装三级分类对象
                for (BaseCategoryView categoryView : entry2.getValue()) {
                    //3.2.1 创建3级分类JSON对象
                    JSONObject jsonObject3 = new JSONObject();
                    //3.2.2 封装3级分类ID
                    jsonObject3.put("categoryId", categoryView.getCategory3Id());
                    //3.2.3 封装3级分类名称
                    jsonObject3.put("categoryName", categoryView.getCategory3Name());
                    jsonObject3List.add(jsonObject3);
                }
                //2.3 将三级分类集合加入到二级分类对象"categoryChild"中
                jsonObject2.put("categoryChild", jsonObject3List);
                jsonObject2List.add(jsonObject2);
            }
            //2.3 将三级分类集合加入到二级分类对象"categoryChild"中
            jsonObject1.put("categoryChild", jsonObject2List);
            return jsonObject1;
        }
        return null;
    }
}
